<?php
/**
 * Created by PhpStorm
 * User: Jhinwy
 * Date: 5/20/24
 * Time: 3:24 PM
 */

namespace App\Services;


use App\Models\Admin;
use Carbon\Carbon;
use Illuminate\Support\Facades\Hash;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;

class AdminService
{

    /**
     * 管理员登录
     *
     * @param $params
     * @return array|string
     */
    public function login($params)
    {
        $account  = trim($params['account'] ?? '');
        $password = trim($params['password'] ?? '');
        if (!$account || !$password) {

            return '账号和密码不能为空';
        }

        if (!$admin = Admin::query()->where('account', $account)->first()) {

            return '账号不存在';
        }
        if (!password_verify($password, $admin->password)) {

            return '密码错误';
        }
        $admin->last_ip = request()->getClientIp();
        $admin->last_at = Carbon::now()->toDateTimeString();
        $admin->save();

        return $this->getToken($account, $password);
    }


    /**
     * 获取Token
     *
     * @param $account
     * @param $password
     * @return array
     */
    private function getToken($account, $password)
    {
        return [
            'token'      => Admin::setGuard()->attempt(['account' => $account, 'password' => $password]),
            'token_type' => Admin::TOKEN_TYPE,
            'expires_in' => $this->getTokenExpiresIn() * 60,
        ];
    }


    /**
     * 获取Token过期时间
     *
     * @return float|int
     */
    private function getTokenExpiresIn()
    {
        return Admin::setGuard()->factory()->getTTL();
    }


    /**
     * 管理员登出
     *
     * @return bool
     */
    public function logout()
    {
        Admin::setGuard()->logout();

        return true;
    }


    /**
     * 获取列表
     *
     * @param $params
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function getList($params)
    {
        $pageSize = $params['page_size'] ?? 50;
        $name     = trim($params['name'] ?? '');

        $query = Admin::query()->select('id', 'name', 'account', 'last_ip', 'last_at', 'status', 'created_at', 'updated_at');
        if ($name) {
            $query->where('name', 'like', '%' . $name . '%');
        }

        return $query->orderBy('updated_at', 'desc')->paginate($pageSize);
    }


    /**
     * 获取所有管理员账号信息
     *
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public function getAll()
    {
        return Admin::query()->select('id', 'name', 'account')->orderBy('created_at')->get();
    }



    /**
     * 管理员详情
     *
     * @return mixed
     */
    public function detail()
    {
        return collect(request()->admin)->except('password');
    }


    /**
     *  创建管理员
     *
     * @param $params
     * @return bool
     */
    public function create($params)
    {
        $name     = trim($params['name'] ?? '');
        $account  = trim($params['account'] ?? '');
        $password = trim($params['password'] ?? '');

        if (!$name || !$account || !$password) {

            return false;
        }

        $admin           = new Admin();
        $admin->name     = $name;
        $admin->account  = $account;
        $admin->password = Hash::make($password);

        return $admin->save();
    }



    /**
     * 禁用 / 启用管理员
     *
     * @param $id
     * @param $status
     * @return bool
     */
    public function disable(int $id, int $status)
    {
        if (!$id) {

            return false;
        }
        if ($status !== Admin::STATUS_ENABLE && $status !== Admin::STATUS_DISABLE) {

            return false;
        }
        if (!$admin = Admin::query()->find($id)) {

            return false;
        }
        $admin->status = $status;

        return $admin->save();
    }


    /**
     * 删除管理员
     *
     * @param $id
     * @return mixed
     */
    public function delete(int $id)
    {
        if (!$id) {

            return false;
        }

        return Admin::query()->where('id', $id)->delete();
    }


    /**
     * 使token失效
     *
     * @return bool
     */
    private function invalidToken()
    {
        if ($token = request()->bearerToken()) {
            try {
                JWTAuth::setToken($token)->invalidate();
            } catch (TokenExpiredException $e) {
                // 因为让一个过期的token再失效，会抛出异常，不需要做任何处理
            }
        }

        return true;
    }
}
